$(document).ready(function(){

	var checkChatServerOn;

	if(chID == ""){
		chID = $("#chID").val();
	} else {
		//CREATE CHAT ELEMENTS
		$("#fixedFooterContainer").append("<div id='chatBox'></div>");
		$("#fixedFooterContainer").append("<div id='tabChat'>Chat | Connecting...</div>");
		$("#chatBox").append("<div id='chatBoxHeader'><span id='showChatUsers' title='People in chat'></span></div>");
		$("#chatBoxHeader").append("<span id='numberChatUsers'>Connecting...</span>");
		$("#chatBox").append("<div id='chatDisplay'></div>");
		$("#chatBox").append("<textarea id='chatInput'></textarea>");
		
		//ELEMENTS TO SHOW USERS IN CHAT
		$("#fixedFooterContainer").append("<div id='peopleChattingBox'></div>");
		$("#peopleChattingBox").append("<div id='peopleChattingBoxHeader'>People in chat<span id='closePeopleChattingBoxHeader' title='Close'></span></div>");
		$("#peopleChattingBox").append("<div id='displayPeopleChatting'></div>");
		
		$("#showChatUsers").click(function() {
			$("#peopleChattingBox").toggle();
		});
		
		// CHAT INPUT IS DISABLED BEOFRE Connected
		$("#chatInput").attr("disabled", "disabled");
		
		$("#tabChat").click(function(){
			$("#chatBox").toggle();
			$("#peopleChattingBox").hide();
		});
		
		
		//----------- SOCKET IO ----------------
		
		try
		{
			var host = window.location.hostname;
			var socket = io.connect('http://' + host + ':8000');
			
			var h_userID = $("#h_userID").val();
			var h_displayName = $("span.sidebarName").text();
			var h_username = "@bob";
			var h_profilePic = $("#h_profilePic").val();
		
			// on connection to server, ask for user's name with an anonymous callback
			socket.on('connect', function(){
			
				// add user to the chat 
				socket.emit('adduser', h_userID, h_displayName, h_username, h_profilePic, chID);
				
				$('#tabChat').text('Chat | Connected');
				
				$("#tabChat").click(function(){
					$("#chatBox").toggle();
					$("#peopleChattingBox").hide();
				});
				
				//ENABLE TEXTAREA
				$("#chatInput").attr("disabled", false);
				
				$("#showChatUsers").show();
				
				$("#closePeopleChattingBoxHeader").click(function() {
					$("#peopleChattingBox").hide();
				});
				
				checkChatServerOn = setInterval(function() {
					checkServerOn();
				}, 3000);
				
				$("#tabChat").click(function(){
					$("#chatBox").toggle();
					$("#peopleChattingBox").hide();
				});
			});

			function htmlEntities(str) {
				return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
			}
			
			function replaceURLWithHTMLLinks(inputText) {
				//URLs starting with http://, https://, or ftp://
				var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
				var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

				//URLs starting with www. (without // before it, or it'd re-link the ones done above)
				var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
				var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
			
				return replacedText;
			}

			
			function DisplayNewMessage(uid, displayName, username, pictureLink, message) {
			
				//CHECK IF SCROLL IS AT THE BOTTOM
				var scrollBottom = false;
					
					if($("#chatDisplay").scrollTop() + $("#chatDisplay").innerHeight() >= $("#chatDisplay")[0].scrollHeight)
                    {
						scrollBottom = true;
                    }

			
					if($("#chatDisplay").text() == "")
					{
						$('#chatDisplay').append("<div class='chatMessageItem uid_" + uid +"'>" +
											"<div class='floatLeft'>" + 
												"<a href='/profile/" + username + "'><img src='/assets/images/profilePics/s/" + pictureLink + "' /></a>" + 
											"</div>" +
											"<div class='chatMessage'>" +
												"<b><a href='/profile/" + username + "'>" + displayName + "</a></b><br />" + replaceURLWithHTMLLinks(htmlEntities(message)) +
											"</div>" +
										 "</div>"
										);
					}
					else
					{
						var previousMessageFromArray = $("div.chatMessageItem").last().attr('class').split(" ");
						var previousMessageFrom = previousMessageFromArray[1];
						
						if(previousMessageFrom == "uid_" + uid)
						{
							$(".uid_" + uid + " > " + "div.chatMessage").last().append("<br />" + replaceURLWithHTMLLinks(htmlEntities(message)));
						}
						else
						{
							$('#chatDisplay').append("<div class='chatMessageItem uid_" + uid +"'>" +
											"<div class='floatLeft'>" + 
												"<a href='/profile/" + username + "'><img src='/assets/images/profilePics/s/" + pictureLink + "' /></a>" + 
											"</div>" +
											"<div class='chatMessage'>" +
												"<b><a href='/profile/" + username + "'>" + displayName + "</a></b><br />" + replaceURLWithHTMLLinks(htmlEntities(message)) +
											"</div>" +
										 "</div>"
										);
						}
					}
					
					
					if(scrollBottom == true)
					{
						$("#chatDisplay").scrollTop($('#chatDisplay').height());
					}
				
			}
			
			function checkServerOn(){
				
				$.ajax({
					url: "php/ajax/checkChatConnection.php",
					success: function(obj)
					{
						if(obj == "false"){
							$('#tabChat').text('Chat | Currently Unavailable');
							$('#chatBox').hide();
							$('#peopleChattingBox').hide();
							$('#tabChat').off('click');
							
							$("#tabChat").css({
								"cursor" : "auto"
							});
							
							clearInterval(checkChatServerOn);
						}
					}
				});
				
			}
			
			// listener, whenever the server emits 'updatechat', this updates the chat body
			socket.on('updatechat', function (uid, displayName, username, pictureLink, message) {
				DisplayNewMessage(uid, displayName, username, pictureLink, message);
			});
			
			//number of users in chat at the start
			socket.on('UsersChatting', function(UsersChatting) {
			
			//DISPLAY NUMBER OF USERS CHATTING
				if(UsersChatting.length == 1)
					$("#numberChatUsers").text(UsersChatting.length + " User");
				else
					$("#numberChatUsers").text(UsersChatting.length + " Users");
			
			//DISPLAY NAMES OF USERS CHATTING
				$("#displayPeopleChatting").text("");
			
				for(var i = 0; i < UsersChatting.length; i++){
					var userItem = UsersChatting[i];
					
					var userID = userItem[0];
					var userDisplayName = userItem[1];
					var userUsername = userItem[2];
					var userPictureLink = userItem[3];

					$("#displayPeopleChatting").append("" +
						"<a href='/profile/" + userUsername + "'><div class='chattingUserItem'>" +
							"<img src='/assets/images/profilePics/s/" + userPictureLink + "' />" +
							"<span class='personChattingDisplayName'>" + userDisplayName + "</span>" +
						"</div></a>"
					);
				}
			
			
			});
			

			// when the client hits ENTER on their keyboard
			$('#chatInput').keyup(function(e) {
				if(e.which == 13) {
					var message = $('#chatInput').val().trim();
					$('#chatInput').val('');
					
					if(message != "")
					{
						socket.emit('sendchat', message);
						DisplayNewMessage(h_userID, h_displayName, h_username, h_profilePic, message);
					}
				}
			});
			
		}
		catch(err)
		{
			$('#tabChat').text('Chat | Currently Unavailable');
			$('#tabChat').off('click');
			
			$("#tabChat").css({
				"cursor" : "auto"
			});
		}

		
	}
});